﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using LogManager.Base;
using LogManager.Base.Data;
using CsvHelper;

namespace LogManager.Models
{
    public class CsvExportService : IEventExportService
    {
        private string _path;
        private IEventTypeService _typeService;

        public CsvExportService(string serverName,string logName,string path, IEventTypeService typeService)
        {
            ServerName = serverName;
            LogName = logName;
            _path = path;
            _typeService = typeService;
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            //Do nothing
        }

        #endregion

        #region Implementation of IEventExportService

        public string LogName { get; set; }

        public string ServerName { get; set; }

        public IEnumerable<IEvent> Export(DateTime start, DateTime end)
        {
            using (var reader = new CsvReader(new StreamReader(_path)))
            {
                reader.Configuration.Delimiter = ';';
                while (reader.Read())
                {
                    DateTime timeStamp = Convert.ToDateTime(reader.GetField("TimeStamp"));
                    
                    //Has to be in requested time range
                    if (timeStamp > start && timeStamp < end)
                    {
                        var @event = new Event
                                         {
                                             Id = reader.GetField("Id"),
                                             Level = reader.GetField("Level"),
                                             ServerName = reader.GetField("ServerName"),
                                             LogName = reader.GetField("LogName"),
                                             Message = reader.GetField("Message"),
                                             TimeStamp = timeStamp,
                                             Type = reader.GetField("Type"),
                                             User = reader.GetField("User")
                                         };

                        var properties = _typeService.Get(@event.Type).CommonProperties;

                        foreach (var property in properties)
                        {
                            @event.Properties[property] = reader.GetField(property);
                        }

                        yield return @event;
                    }
                }
            }
        }

        #endregion
    }
}